//
//  XJOrderFinishViewController.m
//  XinJiangMall
//
//  Created by RaoBo on 2018/5/28.
//  Copyright © 2018年 Tzyang. All rights reserved.
//

#import "XJOrderFinishViewController.h"

// View
#import "XJMyOrderCell.h"
#import "XJMyOrderSectionHeaerView.h"
#import "XJMyOrderSectionFooterView.h"
#import "RBRefreshHeader.h"
#import "RBRefreshFooter.h"

#import "RBNoDataView.h"

//Model
#import "XJMyOrderBigModel.h"

// controller
#import "XJAfterSaleViewController.h" // 申请售后
#import "XJOrderDetailViewController.h"

@interface XJOrderFinishViewController() <UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong)UITableView *tableView;

@property(nonatomic, strong) NSMutableArray <XJMyOrderBigModel *>*orderArray;
@property(nonatomic, strong) RBNoDataView *nodataView;

@end

@implementation XJOrderFinishViewController

#pragma mark - 一 lazy
- (UITableView *)tableView{
    if (!_tableView) {
        // 如果是iphoneX的话 tableView 的高度 = 屏高 - 顶部导航64 - 底部状态栏 34
        // √https://github.com/coderketao/iOS11-iPhoneX
        CGFloat kHT_TabbarSafeBottomMargin = 0;
        if (KHeight > 667) {
            kHT_TabbarSafeBottomMargin = 34;
        }
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, KWidth, KHeight - XJTopNavH - kHT_TabbarSafeBottomMargin) style:(UITableViewStylePlain)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
        _tableView.rowHeight = 120;
        _tableView.sectionHeaderHeight = 40;
        _tableView.sectionFooterHeight = 100;
        
        
        [_tableView registerClass:[XJMyOrderCell class] forCellReuseIdentifier:@"XJMyOrderCellId"];
        [_tableView registerClass:[XJMyOrderSectionHeaerView class] forHeaderFooterViewReuseIdentifier:@"XJMyOrderSectionHeaerViewId"];
        [_tableView registerClass:[XJMyOrderSectionFooterView class] forHeaderFooterViewReuseIdentifier:@"XJMyOrderSectionFooterViewId"];
        
        _tableView.tableFooterView = [UIView new];
    }
    return _tableView;
}


- (NSMutableArray<XJMyOrderBigModel *> *)orderArray {
    if (!_orderArray) {
        _orderArray = [NSMutableArray array];
    }
    return _orderArray;
}

- (RBNoDataView *)nodataView {
    if (!_nodataView) {
        _nodataView = [RBNoDataView new];
    }
    return _nodataView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = @"已完成";

    [self.view addSubview:self.tableView];
    
    
    [self requestFinishData];
    
    [self setupRefresh];
}
- (void) setupRefresh {
    
    self.tableView.mj_header = [RBRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestFinishData)];
}

#pragma mark - 三 UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.orderArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.orderArray[section].goods.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    XJMyOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"XJMyOrderCellId"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
   XJMyOrderGoodsModel *goodsM = self.orderArray[indexPath.section].goods[indexPath.row];
    
    
    NSString *imgStr = goodsM.cover;
    NSString *name = goodsM.goods_name;
    NSString *price = goodsM.price;
    NSString *count = goodsM.quantity;
    [cell configureXJMyOrderCellWithImgStr:imgStr name:name price:price count:count];
    
    return cell;
}

#pragma mark  - UITableViewDelegate
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    XJMyOrderSectionHeaerView *sectionHeaderV = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"XJMyOrderSectionHeaerViewId"];
    
    
    XJMyOrderBigModel *bigM = self.orderArray[section];
    
    [sectionHeaderV configureMyOrderSectionHeaderViewShopName:bigM.shop_name rightTitle:bigM.state_name];
    
    return sectionHeaderV;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    XJMyOrderSectionFooterView *sectionFooterV = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"XJMyOrderSectionFooterViewId"];
    
    XJMyOrderBigModel *bigM = self.orderArray[section];

    [sectionFooterV configureXJMyOrderSectionFooterViewCount:bigM.goods_count price:bigM.order_amount freight:bigM.express_amount bntArray:bigM.btns];
    
    sectionFooterV.myOrderSectionFooterViewFirstButtonBlock = ^(XJMyOrderBtnModel *btnModel) {
        XJLog(@"%@",btnModel);
        if ([btnModel.code isEqualToString:kOrderBtnRefund]) {
            
            XJAfterSaleViewController *afterVC = [XJAfterSaleViewController new];
            afterVC.orderSN = bigM.order_sn;
            afterVC.order_goods_id = [bigM.goods firstObject].goods_id;
            [self.navigationController pushViewController:afterVC animated:YES];
        }
    };
    
    sectionFooterV.myOrderSectionFooterViewSecondButtonBlock = ^(XJMyOrderBtnModel *btnModel) {
        XJLog(@"%@",btnModel);
        
        [self requestDeleteDataWithBigModel:bigM];
    };
    return sectionFooterV;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    XJOrderDetailViewController *orderDetailVC = [[XJOrderDetailViewController alloc] init];
    
    //请求参数
    XJMyOrderBigModel *bigM = self.orderArray[indexPath.section];
    orderDetailVC.orderSN = bigM.order_sn;
    
    orderDetailVC.orderDetailType = XJOrderDetailTypeFinish;
    [self.navigationController pushViewController:orderDetailVC animated:YES];
}


#pragma mark - 让tableView的sectionHeader 随cell一起移动
//https://www.jianshu.com/p/264bd4d33c7f
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    if (self.tableView == scrollView) {
        CGFloat sectionHeaderHeight =  40;
        if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
        } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
        }
    }
}


#pragma mark - 四 网络请求
- (void)requestFinishData {
    //3 待评价
    
    [self.orderArray removeAllObjects];
    
    [XJHttpTool requestOrderOrderListsWithType:@"4" page:@"1" successH:^(id responseObjc) {
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        if([code isEqualToString:@"0"]){
            
            NSArray *orders = responseObjc[@"data"][@"content"][@"order"];
            if (orders.count) {
                self.orderArray =  [XJMyOrderBigModel mj_objectArrayWithKeyValuesArray:orders];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.tableView reloadData];
                    [self.nodataView rb_hideNoDataView];
                });
            }else {
                [self.nodataView rb_showNoDataViewInView:self.tableView message:@"没有数据" placeHolder:@"暂无数据.png"];
            }
        }else{
            XJLog(@"出错了:%@",responseObjc);
        }
        
        
        [self.tableView.mj_header endRefreshing];
    } failH:^(NSError *error) {
        
        [JRToast showWithText:[error localizedDescription]];
        [self.tableView.mj_header endRefreshing];
    }];
}

/**删除订单*/
- (void)requestDeleteDataWithBigModel:(XJMyOrderBigModel *)bigM {
    [XJHttpTool requestOrderDeleteOrderWithOrderSN:bigM.order_sn successH:^(id responseObjc) {
        
        //不管三七二十一直接刷新
        [self requestFinishData];
        
    } failH:^(NSError *error) {
        [JRToast showWithText:[error localizedDescription]];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
